import dayjs from 'dayjs';
import moment from 'moment';

/**
 * 数组转树状
 */
export function arr2tree(list = []) {
  const data = JSON.parse(JSON.stringify(list));
  const result = [];
  if (!Array.isArray(data)) {
    return result;
  }
  data.forEach(item => {
    delete item.children;
  });
  const map = {};
  data.forEach(item => {
    map[item.id] = item;
  });
  data.forEach(item => {
    const parent = map[item.pid];
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      result.push(item);
    }
  });
  return result;
}

/**
 * 获取指定元素的所有子级节点
 */
export function getAllChildList(tree, id) {
  const result = [];
  const deep = (data) => {
    for (let i = 0, len = data.length; i < len; i++) {
      const v = data[i];
      result.push(v.id);
      if (v.children && v.children.length) {
        deep(v.children);
      }
    }
  };
  const find = (data) => {
    for (let i = 0, len = data.length; i < len; i++) {
      const v = data[i];
      if (v.id === id) {
        deep(v.children || []);
        break;
      } else if (v.children && v.children.length) {
        find(v.children);
      }
    }
  };
  find(tree);
  return result;
}

/**
 * 获取指定元素的所有父级节点
 */
export function getAllParentList(data, id) {
  const result = [];
  const deep = (id, isRoot) => {
    for (let i = 0, len = data.length; i < len; i++) {
      const v = data[i];
      if (v.id === id) {
        if (!isRoot) {
          result.push(v.id);
        }
        if (v.pid && v.pid !== '0') {
          deep(v.pid, false);
        }
        break;
      }
    }
  };
  deep(id, true);
  return result;
}

/**
 * 获取区间日期
 */
export function formatRangeDate(rangeDate) {
  if (!rangeDate) {
    return {start: undefined, end: undefined};
  }
  return {
    start: dayjs(rangeDate[0]).format('YYYY-MM-DD') + ' 00:00:00',
    end: dayjs(rangeDate[1]).format('YYYY-MM-DD') + ' 23:59:59'
  };
}

// 默认字体为微软雅黑 Microsoft YaHei,字体大小为 14px
export function getTextWidth(text, font = "14px Microsoft YaHei") {
  const canvas = document.createElement("canvas");
  let context = canvas.getContext("2d");
  context.font = font
  let textmetrics = context.measureText(text)
  return textmetrics.width;
}

export function getWidthMap(data) {
// 定义一个 Map 接收每列的长度值
  let widthMap = new Map()
  // columns 为动态表格的表头数组 data为展示数据的数组
  //作用是遍历所有数据拿到长度最长的一条记下他的宽度
  data.forEach(target => {
    for (let key in target) {
      if (target.hasOwnProperty(key)) {
        let keyWidth = getTextWidth(target[key])
        let curValue = widthMap.get(key) || 0
        // 字段有值就放入数组
        widthMap.set(key, Math.max(curValue, keyWidth))
      }
    }
  })
  return widthMap;
}

export function nowrapColumns(columns, data) {
  if (data.length > 0) {
    let widthMap = getWidthMap(data);
    columns.map(item => {
      let textWidth = item.width ? item.width : getTextWidth(item.title);
      let currWidth = item.width ? item.width : widthMap.get(item.dataIndex);
      if (currWidth <= textWidth && item.dataIndex) {
        widthMap.set(item.dataIndex, textWidth)
      }
      return item.width = item.width ? item.width : (Math.ceil(widthMap.get(item.dataIndex)) + 35);
    });
  }
  return columns;
}

export function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}

/**
 * @param type 'today' | 'week' | 'month' | 'year'
 */
export function getTimeDistance(type) {
  const now = new Date();
  const oneDay = 1000 * 60 * 60 * 24;

  if (type === 'today') {
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    return [moment(now), moment(now.getTime() + (oneDay - 1000))];
  }

  if (type === 'week') {
    let day = now.getDay();
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);

    if (day === 0) {
      day = 6;
    } else {
      day -= 1;
    }

    const beginTime = now.getTime() - day * oneDay;

    return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
  }
  const year = now.getFullYear();

  if (type === 'month') {
    const month = now.getMonth();
    const nextDate = moment(now).add(1, 'months');
    const nextYear = nextDate.year();
    const nextMonth = nextDate.month();

    return [
      moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
      moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000),
    ];
  }

  return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
}

